package com.vip.jwt.common.utils.aliyun;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vip.jwt.common.utils.sign.AliyunSignUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 阿里云短信验证码工具类
 */
public class AliyunSmsUtil {

    @Getter
    private static String ID;

    @Getter
    private static String SECRET;

    @Value("${aliyun-access-id}")
    public void setID(String id) {
        ID = id;
    }

    @Value("${aliyun-access-secret}")
    public void setSecret(String secret) {
        SECRET = secret;
    }

    /**
     * 发送短信
     * @param phone 手机号
     * @param signName 阿里云TemplateCode 获取途径：阿里云控制台短信服务模板签名（将中文进行Unicode编码）
     * @param templateCode 阿里云TemplateCode 获取途径：阿里云控制台短信服务模板ID
     * @return
     */
    public static String sendSms(String phone,String signName,String templateCode,Map<String,Object> param){
        String url = "https://dysmsapi.aliyuncs.com/?Signature=";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        // 这里一定要设置GMT时区
        df.setTimeZone(new SimpleTimeZone(0, "GMT"));
        Map<String, String> paras = new HashMap<String, String>();
        // 1. 系统参数
        paras.put("SignatureMethod", "HMAC-SHA1");
        paras.put("SignatureNonce", UUID.randomUUID().toString());
        paras.put("AccessKeyId", ID);
        paras.put("SignatureVersion", "1.0");
        paras.put("Timestamp", df.format(new Date()));
        paras.put("Format", "JSON");
        // 2. 业务API参数（短信验证码）
        paras.put("Action", "SendSms");
        paras.put("Version", "2017-05-25");
        paras.put("RegionId", "cn-hangzhou");
        paras.put("PhoneNumbers", phone);
        paras.put("SignName", signName);
        String templateParam = JSONObject.toJSONString(param);
        paras.put("TemplateParam", templateParam);
        paras.put("TemplateCode", templateCode);
        // 3. 去除签名关键字Key
        if (paras.containsKey("Signature"))
            paras.remove("Signature");
        String signAndParams = "";
        signAndParams = AliyunSignUtil.getSign(SECRET,paras);
        return HttpRequest.get(url+signAndParams).execute().body();
    }

}
